package controller;

import dao.TeacherService;
import entity.Teacher;
import exception.BaseException;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/t")
public class TeacherRead extends HttpServlet {
    @Override
    protected  void doGet(HttpServletRequest request, HttpServletResponse respsonse)throws ServletException, IOException {
        JSONObject message_jsonObj = new JSONObject();
        respsonse.setContentType("application/json;charset=UTF-8");
        String req_jsonStr = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        if (req_jsonObj==null) {
            message_jsonObj.put("message", "未收到请求信息！");
            respsonse.getWriter().println(message_jsonObj);
            return;
        }
        try {
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            Collection<Teacher> teacherList= TeacherService.getInstance().findAll(conditionList);
            String teachers_json= JSON.toJSONString(teacherList, JSONWriter.Feature.ReferenceDetection);
            respsonse.getWriter().println(teachers_json);
        }catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            respsonse.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常！");
            respsonse.getWriter().println(message_jsonObj);
            e.printStackTrace();
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常！");
            respsonse.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }
}